#!/bin/bash

# --- Configuration ---
PID_FILE="app.pid"
# ---------------------

echo "Stopping the application..."

if [ ! -f "$PID_FILE" ]; then
    echo "INFO: PID file not found. The application may not be running."
    # Fallback: try to find the process by the JAR name
    PID=$(pgrep -f "aibox-pro.jar")
    if [ -z "$PID" ]; then
        echo "INFO: No running process found for 'aibox-pro.jar'. Stop command finished."
        exit 0
    else
        echo "INFO: Found running process with PID $PID by searching for the jar name."
    fi
else
    PID=$(cat "$PID_FILE")
fi

if [ -z "$PID" ]; then
    echo "ERROR: Could not determine the Process ID to stop."
    exit 1
fi

echo "Stopping process with PID: $PID"
kill "$PID"

# Wait for the process to terminate gracefully
for i in {1..5}; do
    if ! ps -p "$PID" > /dev/null; then
        break
    fi
    echo "Waiting for process to stop... ($i)"
    sleep 1
done

# If it's still running, force kill it
if ps -p "$PID" > /dev/null; then
    echo "Process did not stop gracefully. Forcing termination with kill -9."
    kill -9 "$PID"
fi

if [ -f "$PID_FILE" ]; then
    rm "$PID_FILE"
fi

echo "Application stopped successfully."
